/*
 * Copyright (c) 2016  西咸新区大数据信息技术服务有限公司版权所有.
 */

package com.otherTest.other;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * 时间类常用工具
 *
 * @author Jeff
 * @version 1.0, 2016-09-05
 */
@SuppressWarnings({"all"})
public class DateUtil {

    /**
     * 格式化时间
     *
     * @param date    时间
     * @param pattern 格式
     * @return 时间串
     */
    public static String getFormatTime(Date date, String pattern) {
        if (StringUtil.isEmpty(pattern))
            pattern = "yyyy-MM-dd HH:mm:ss";
        if (date == null)
            date = new Date();
        DateFormat format = new SimpleDateFormat(pattern);
        return format.format(date);
    }

    /**
     * 将时间字符串转化为日期
     *
     * @param date    时间字符串
     * @param pattern 格式
     * @return 时间
     * @throws ParseException
     */
    public static Date formatDate(String date, String pattern) throws ParseException {
        if (StringUtil.isEmpty(pattern))
            pattern = "yyyy-MM-dd HH:mm:ss";
        if (StringUtil.isEmpty(date))
            return null;
        DateFormat format = new SimpleDateFormat(pattern);
        return format.parse(date);
    }


    /**
     * 获取指定日期是星期几
     * 参数为null时表示获取当前日期是星期几
     *
     * @param date 时间
     * @return 星期几
     */
    public static String getWeekOfDate(Date date) {
        String[] weekOfDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
        Calendar calendar = Calendar.getInstance();
        if (date != null) {
            calendar.setTime(date);
        }
        int w = calendar.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0) {
            w = 0;
        }
        return weekOfDays[w];
    }

    /**
     * 计算两个日期之间的间隔
     *
     * @param startDate 开始时间
     * @param endDate   结束时间
     * @return 时间间隔
     */
    public static int daysBetween(Date startDate, Date endDate) throws ParseException {
        Date sd = formatDate(getFormatTime(startDate, "yyyyMMdd"), "yyyyMMdd");
        Date ed = formatDate(getFormatTime(endDate, "yyyyMMdd"), "yyyyMMdd");
        Calendar cal = Calendar.getInstance();
        cal.setTime(sd);
        long time1 = cal.getTimeInMillis();
        cal.setTime(ed);
        long time2 = cal.getTimeInMillis();
        long between_days = (time2 - time1) / (1000 * 3600 * 24);
        return Integer.parseInt(String.valueOf(between_days));
    }

    /**
     * 将时间规划到时间块的起始时间
     *
     * @param date 源时间
     * @param step 步长（minute）
     * @return 目标时间
     */
    public static Date getStepDate(Date date, int step) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        int minute = cal.get(Calendar.MINUTE);
        int offset = (minute / step) * step;

        long timestamp = (date.getTime() / (1000 * 60)) * (1000 * 60) - (minute - offset) * 60 * 1000;
        return new Date(timestamp);
    }

}
